/*
 *	Maximum division & minimum multiplination functions
 *
 *	Copyright (C) 2011 XiaoJSoft Studio. All Rights Reserved.
 *	Copyright (C) Ji WenCong <whs_jwc@163.com>
 *
 *	This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU General Public License
 *	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "../include/mmdiv.h"

/*
 *	long double lfabs(long double x);
 *
 *	To get the absolute value of long double value x.
 *
 *	x		->	A number.
 */
long double lfabs(long double x)
{
	if (x < 0) {
		return(-x);
	}

	return(x);
}

/*
 *	long double mdiv(long double x, long double y);
 *
 *	To get maximum division of two numbers.
 *
 *	x		->	One number,
 *	y		->	Another number.
 */
long double mdiv(long double x, long double y)
{
	int fNeg;
	long double ldNum1, ldNum2;

	/*  is x or y a negative number?  */
	fNeg = (x<0 || y<0) ? 1 : 0;

	/*  To get abs(x) and abs(y)  */
	ldNum1 = lfabs(x);
	ldNum2 = lfabs(y);

	/*  if x or y equals to zero, returning one  */
	if ((ldNum1 == 0) || (ldNum2 == 0)) {
		return(1);
	}

	/*  Iterating  */
	while (ldNum1 != ldNum2) {
		if (ldNum1 > ldNum2) {
			ldNum1 = ldNum1 - ldNum2;
		} else if (ldNum1 < ldNum2) {
			ldNum2 = ldNum2 - ldNum1;
		}
	}

	return((fNeg == 1) ? -ldNum1 : ldNum1);
}

/*
 *	long double mmul(long double x, long double y)
 *
 *	To get minimum multiplination of two numbers.
 *
 *	x		->	One number,
 *	y		->	Another number.
 */
long double mmul(long double x, long double y)
{
	int fNeg;
	long double ldDiv, ldNum1, ldNum2;

	/*  is x or y a negative number?  */
	fNeg = (x<0 || y<0) ? 1 : 0;

	/*  To get abs(x) and abs(y)  */
	ldNum1 = lfabs(x);
	ldNum2 = lfabs(y);

	/*  To get maximum division of two numbers  */
	ldDiv = mdiv(ldNum1, ldNum2);

	if (ldDiv == 0) {
		return(0);
	} else {
		return((fNeg == 1) ? -ldNum1 * ldNum2 / ldDiv : ldNum1 * ldNum2 / ldDiv);
	}
}

